package com.zjh.springsecurity09remberme.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;

import javax.sql.DataSource;
import java.util.UUID;

/**
 * @Auther: zjh
 * @Date: 2025/9/14 - 09 - 14 - 22:10
 * @Description: com.zjh.springsecurity09remberme.config
 * @version: 1.0
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    public SecurityConfig(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails userDetails = User.builder().username("root").password("{noop}123").roles("ADMIN").build();
        return new InMemoryUserDetailsManager(userDetails);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService());
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                //开启记住我功能。
                .rememberMe()
//                .rememberMeServices( rememberMeServices())
//                .tokenRepository(new JdbcTokenRepositoryImpl())
                .and()
                .csrf().disable();
    }
    private final  DataSource dataSource;

    @Bean
    public RememberMeServices rememberMeServices(){
        JdbcTokenRepositoryImpl repository = new JdbcTokenRepositoryImpl();
        repository.setDataSource(dataSource);
        repository.setCreateTableOnStartup(true);

        return new PersistentTokenBasedRememberMeServices(UUID.randomUUID().toString(), userDetailsService(), repository);
    }
}
